package api

import (
	"log"
	"strconv"

	"gitee.com/dingiyan/goMyAdmin/db"
	"gitee.com/dingiyan/goMyAdmin/service/dialect"
	"github.com/gin-gonic/gin"
)

// api create database
// 在一个数据连接参数上执行创建数据库操作
// 连接id前端提供
func CreateDatabase(c *gin.Context) {
	var body struct {
		// 数据源id
		DsId uint `json:"dsId"`
		// 要创建的数据库名称
		DatabaseName string `json:"databaseName"`
	}

	if err := c.ShouldBindJSON(&body); err != nil {
		log.Println(err)
		c.JSON(200, resError(1, "参数错误"))
		return
	}

	datasourcesRecord, err := db.GetServerById(body.DsId)
	if err != nil || datasourcesRecord == nil {
		log.Println(err)
		c.JSON(200, resError(2, "查询数据源记录出错！"))
		return
	}

	dbm := dialect.GetDialect(dialect.DialectMysql)
	config := serverToDatasourcesConfig(datasourcesRecord)
	_, err1 := dbm.ConnectDatasources(&config)

	if err1 != nil {
		log.Println(err1)
		c.JSON(200, resError(3, "连接数据库出错"))
		return
	}
	if err := dbm.CreateDatabase(body.DatabaseName, nil); err != nil {
		log.Println(err)
		c.JSON(200, resError(4, "创建数据库出错"))
		return
	}
	c.JSON(200, success(true))

}

// 获取一个ds连接的数据库列表
func GetDatabaseList(c *gin.Context) {

	var dsId = c.Query("dsId")

	id, err := strconv.Atoi(dsId)
	if err != nil {
		log.Println(err)
		c.JSON(200, resError(1, "参数错误"))
		return
	}
	datasourcesRecord, err := db.GetUsersServerById(getUserId(c), uint(id))
	if err != nil || datasourcesRecord == nil {
		log.Println(err)
		c.JSON(200, resError(2, "查询数据源记录出错！"))
		return
	}

	dialectManager := dialect.GetDialect(dialect.DialectMysql)
	config := serverToDatasourcesConfig(datasourcesRecord)

	dsConnection, err := dialectManager.ConnectDatasources(&config)
	if err != nil {
		log.Println(err, dsConnection)
		c.JSON(200, resError(3, "连接数据库出错"))
		return
	}
	// mysql := dialectManager.(dialect.MySQL)

	list, err := dialectManager.GetDatabases()
	if err != nil {
		log.Println(err)
		c.JSON(200, resError(4, "查询列表出错"))
		return
	}
	c.JSON(200, success(list))

}

// 删除一个数据库
func DropDatabase(c *gin.Context) {
	var body struct {
		DsId         uint   `json:"dsId"`
		DatabaseName string `json:"databaseName"`
	}
	if err := c.ShouldBindJSON(&body); err != nil {
		log.Println(err)
		c.JSON(200, resError(1, "参数错误"))
		return
	}
	datasourcesRecord, err := db.GetServerById(body.DsId)
	if err != nil || datasourcesRecord == nil {
		log.Println(err)
		c.JSON(200, resError(2, "查询数据源记录出错！"))
		return
	}
	dialectManager := dialect.GetDialect(dialect.DialectMysql)
	config := serverToDatasourcesConfig(datasourcesRecord)
	dsConnection, err := dialectManager.ConnectDatasources(&config)
	if err != nil {
		log.Println(err, dsConnection)
		c.JSON(200, resError(3, "连接数据库出错"))
		return
	}
	if err := dialectManager.DropDatabase(body.DatabaseName); err != nil {
		log.Println(err)
		c.JSON(200, resError(4, "删除数据库出错"))
		return
	}
	c.JSON(200, success(true))
}
